const mongoose = require('../utils/db')

//创建商品Schema
const shopSchema = new mongoose.Schema({
    name:String,
    price:Number,
    num:Number
})

//创建商品模板
var Shop = mongoose.model('shops',shopSchema)

//从数据库拿到list
const findShop = () =>{
    return new Promise((resolve,reject)=>{
        Shop.find((err,docs) =>{
            if(err) reject(err)
            else resolve(docs)
        })
    })
}

//插入一条数据
const insertShop = (shopinfo) =>{
    const shop = new Shop(shopinfo)
    return new Promise((resolve, reject) =>{
        shop.save((err,doc) =>{
            if(err) reject(err)
            else resolve(doc)
        })
    })
}

//更改一条数据
const updateShop = (oneshop) =>{
    return new Promise((resolve, reject) =>{
        Shop.update({_id:oneshop.id},{$set:{name:oneshop.name,price:oneshop.price,num:oneshop.num}},(err,dos) =>{
            if(err) reject(err)
            else resolve(dos)
        })
    })
}

//删除一条数据
const removeShop = (lishop) =>{
    return new Promise((resolve, reject) =>{
        Shop.remove({_id:lishop.idx},(err,dos) =>{
            if(err) reject(err)
            else resolve(dos)
        })
    })
}

//暴露findShop
module.exports = {
    findShop,
    insertShop,
    updateShop,
    removeShop
}